import asyncio
from app.core.logger import logger
from app.crud.xm.monitor_buy import get_monitor_buy_max_price
from app.core.task_db import TaskDBSession
from tasks.workers.xm_price_check import check_xm_price
from app.core.utils import yuan_str_to_cents, cents_to_yuan_str
from tasks.workers.xm_buyer import buy_archive

class ArchiveTaskManager:
    """
    XM藏品监控任务并发调用管理器
    """
    def __init__(self, max_concurrency: int = 10):
        self.semaphore = asyncio.Semaphore(max_concurrency)
    
    async def run_tasks(self, archiveIds: list[int]):
        """
        并发执行任务列表
        """
        tasks = [self._run_single_task(archiveId) for archiveId in archiveIds]
        await asyncio.gather(*tasks, return_exceptions=True)

    async def _run_single_task(self, archiveId: int):
        """
        单个任务执行
        """
        async with self.semaphore:
            try:
                async with TaskDBSession() as db_session:
                    monitor_buy = await get_monitor_buy_max_price(
                        session=db_session,
                        archiveId=archiveId,
                    )
                if not monitor_buy:
                    logger.info(f"没有监控挂单记录 archiveId: {archiveId}")
                    return
                logger.info(f"Checking price for {monitor_buy.archiveName}, archiveId: {archiveId}")
                # 检查当前价格是否低于挂单价格
                xm_goods = await check_xm_price(archiveId, monitor_buy.platformId)

                if yuan_str_to_cents(xm_goods["goodsPrice"]) <= monitor_buy.buyPrice:
                    await buy_archive(
                        uid=monitor_buy.uid,
                        goodsId=xm_goods["goodsId"],
                        goodsPrice=xm_goods["goodsPrice"],
                        monitorBuyId=monitor_buy.id,
                    )
                else:
                    logger.info(f"当前价格 {xm_goods['goodsPrice']} 未低于挂单价格 {cents_to_yuan_str(monitor_buy.buyPrice)}")
            except Exception as e:
                logger.error(f"执行任务 archiveId={archiveId} 时出错: {e}")